/**
 * @Author: Sun Rising 
 * @Date: 2020-06-14 18:44:22 
 * @Last Modified by: Sun Rising
 * @Last Modified time: 2020-06-25 18:35:33
 * @Description: 自定义input简单实现
 */
<template>
  <input ref="input" :type="type" v-bind:class="{'error':errorStyle}" :password="password" :placeholder="placeholder" v-model="inputValue" @blur="onBlur" @input="onInput" />
</template>

<script>
export default {
  name: "sunInput",
  props: {
    // 双向绑定
    value: {
      type: String,
      default: ""
    },
    // 标签类型
    type: {
      type: String,
      default: "text"
    },
    // 反显内容
    password: {
      type: Boolean,
      default: false
    },
    // 提示
    placeholder: {
      type: String,
      default: ""
    }
  },
  inject: {
    sunFormItem: {
      default: ""
    }
  },
  data() {
    return {
      // 输入的值
      inputValue: "",
      // 错误样式
      errorStyle: false
    };
  },
  watch: {
    value: {
      handler(val) {
        this.inputValue = val;
      },
      immediate: true
    },
    inputValue: {
      handler(val) {
        this.$emit("input", val);
      }
    }
  },
  methods: {
    // 显示错误样式
    showErrorStyle(val) {
      this.errorStyle = val;
    },
    // 失去焦点通知
    onBlur(e) {
      if (this.sunFormItem) this.dispatch("sunFormItem", "sun.form.blur", e.detail.value);
    },
    // 输入时通知
    onInput(e) {
      this.errorStyle = false;
      if (this.sunFormItem) this.dispatch("sunFormItem", "sun.form.input", e.detail.value);
    },
    // 查找目标组件并调用目标函数
    dispatch(componentName, eventName, params) {
      var parent = this.$parent || this.$root;
      var name = parent.$options.name;

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent;
        if (parent) {
          name = parent.$options.name;
        }
      }

      if (parent) {
        parent.$emit.apply(parent, [eventName].concat(params));
      }
    }
  }
};
</script>

<style lang="less" scoped>
.error {
  color: red;
}
</style>
